import os
import yaml
import shutil

def execute(opts):

# variabloj

    ARG=opts['destination'] + '/' + opts['echo']

    # catch duplicated project names
    n   = 0
    f   = open(opts['config'],'r')
    cdc = yaml.load(f)
    with open(opts['config'], 'r') as skeleto:
        for line in skeleto:
            if n == 0:
                if os.path.exists(ARG):
                    try:
                        curlist = os.listdir(opts['destination'])
                        matching = [s for s in curlist if opts['echo'] + "_" in s]
                        sortlist = []
                        for item in matching:
                            sortlist.append(int(item.split("_")[1]))
                        n = max(sortlist) +1
                        ARG = ARG + '_' + str(n)
                    except: 
                        n = n + 1
                        ARG = ARG + '_' + str(n)
                else:
                    n = 1

        # create the directory tree
        for key,val in cdc.items():
            if key == opts['type']:
                for d in val:
                    for act,dest in d.items():
                        if act == 'mkdir':
                            target = ARG + '/' + dest
                            os.makedirs(target.rstrip(),exist_ok=True)
                        elif act == 'copyfile':
                            target = ARG + '/' + dest.split(':')[1]
                            shutil.copyfile(dest.split(':')[0], target )
                        elif act == 'symdir':
                            plug   = dest.split(':')[0]
                            socket = ARG + '/' + dest.split(':')[1]
                            os.symlink(plug.replace('%COMMON%', opts['shared']).rstrip(), socket.rstrip(), target_is_directory=True )
                        elif act == 'symfile':
                            plug   = dest.split(':')[0]
                            socket = ARG + '/' + dest.split(':')[1]
                            os.symlink(plug.replace('%COMMON%', opts['shared']).rstrip(), socket.rstrip(), target_is_directory=False )
                        else:
                            break
